<template>
	<view class="reg-page">
		<view style="padding: 0 10px;margin-top: 10px;">
			<view class="form-sty">
				<text class="input-title bi-shu-sty">头像</text>
				<!-- 				<uni-file-picker :disabled="btnFla" class="img-sty" :auto-upload="false" limit="1" mode="grid"
					:disablePreview="false" v-model="imgList" file-mediatype="image" :sizeType="sizeType" ref="imgs"
					@select="imgSelect" @progress="imgProgress" @success="imgSuccess" @fail="imgFail" @delete="delImg"> -->
				<!-- </uni-file-picker> -->
				<imgComprss @imgSuccess="imgSuccess" @delImg="delImg"></imgComprss>
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">学员姓名</text>
				<input v-if="!formData._id" class="input-sty" :maxlength="4" type="text" v-model="formData.stdNm"
					placeholder="姓名" :disabled="btnFla">
				<!-- 				<text class="input-sty is-disabled">{{formData.stdNm}}</text> -->
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">学员证件号(户口本)</text>
				<input v-if="!formData._id" class="input-sty" type="text" v-model="formData.learnerId" placeholder="证件号"
					:disabled="btnFla" :maxlength="18">
				<!-- 				<text class="input-sty is-disabled">{{formData.stdNm}}</text> -->
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">性别</text>
				<uni-data-select style="width: 50%;" class="input-sty" v-model="formData.gender" :localdata="items"
					:clear="false" :disabled="btnFla" />
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">年龄</text>
				<input class="input-sty" type="text" v-model="formData.age" placeholder="年龄" :disabled="btnFla"
					:maxlength="3">
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">身高</text>
				<input class="input-sty" type="text" v-model="formData.height" placeholder="身高" :disabled="btnFla"
					:maxlength="3">
			</view>
			<view class="form-sty">
				<text class="input-title bi-shu-sty">体重</text>
				<input class="input-sty" type="text" v-model="formData.weight" placeholder="体重" :disabled="btnFla"
					:maxlength="3">
			</view>
			<view v-if="btnFla" style="margin: 150px auto;text-align: center;">
				<view class="btn-area" @click="editBtn" style="display: inline-block;">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">编辑</view>
				</view>
			</view>
			<view style="display: flex;margin-top: 35px;" v-else>
				<view class="btn-area" @click="restBtn">
					<view class="btn-sty">重置</view>
				</view>
				<view class="btn-area" @click="confirmBtn">
					<view class="btn-sty" style="background: #fc993b;color:#fff;">确认</view>
				</view>

			</view>

		</view>
	</view>
</template>

<script>
	import {
		cheackUser,
		checkFontRule,
		verifyForm
	} from '@/utils/baseFn.js';
	import imgComprss from '@/components/img-comprs-compt/img-comprs-compt.vue';
	const db = uniCloud.database()
	const items = [{
			value: '0',
			text: '女'
		},
		{
			value: '1',
			text: '男'
		}
	]
	export default {
		components: {
			imgComprss
		},
		data() {
			return {
				formData: {
					portrait: '',
					learnerId: '',
					stdNm: '',
					gender: '',
					age: '',
					height: '',
					weight: '',
					classIds: '', // 参与的课程集
					phone: '', // 报名人手机
					userId: '' // 报名人id
				},
				userInfo: {},
				imgList: [],
				sizeType: ['original', 'compressed'],
				items: items,
				btnFla: false,
				tranObj: {}
			}
		},
		onLoad(e) {
			const _this = this
			this.tranObj = JSON.parse(e.parm)
			console.log(this.tranObj)
			uni.getStorage({
				key: 'userInfo',
				success: function(res) {
					if (res.data) {
						// const file = res.data.portrait.split(',')
						_this.userInfo = res.data
						// _this.imgList = [{
						// 	fileID: `${_this.$baseImgUrl}${file[0]}`,
						// 	url: `${_this.$baseImgUrl}${file[0]}`,
						// 	name: file[1]
						// }]
					}
				},
				fail: function(res) {}
			})
		},
		created() {},
		mounted() {},
		methods: {
			getCourseRegister(userInfo, classId, parm) {
				return new Promise((resolve, reject) => {
					const where =
						`"applicationPhone"=="${userInfo.phone}"&&"courseId"=="${classId}"&&"learnerId"=="${parm.learnerId}"`
					return db.collection('course-registration').where(where)
						.field('applicationPhone,courseId,learnerNm,payStatus').get().then((res) => {
							const data = res.result.data[0]
							if (data) {
								uni.showModal({
									content: `${data.learnerNm}已报名，${data.payStatus == 0 ? '未支付':'已支付'}`,
									showCancel: false
								})
								resolve(false);
							} else {
								return db.collection('course-registration').add(parm).then((res) => {
									uni.showToast({
										title: '报名成功'
									})
									resolve(true);
								}).catch((err) => {
									uni.showModal({
										content: err.message || '请求服务失败',
										showCancel: false
									})
								})
							}
							console.log(res)
						}).catch((err) => {
							uni.showModal({
								content: err.message || '请求服务失败',
								showCancel: false
							})
						})
				})
			},
			// 报名成功后将课程id和学员证件号存入更新用户表
			updateUserInfo(parm) {
				const _this = this
				let cl = this.userInfo.classIds ? JSON.parse(this.userInfo.classIds) : []
				// let sl = this.userInfo.studentIds ? this.userInfo.studentIds.split(',') : []
				cl.push({
					cid: parm.cid,
					sid: parm.sid,
					phone: this.userInfo.phone
				})
				const data = {
					classIds: JSON.stringify(cl),
					// studentIds: sl.join(','),
					updated_date: new Date().getTime()
				}
				return db.collection('user-MGMT').doc(this.userInfo._id).update(data).then((res) => {
					db.collection('user-MGMT').doc(this.userInfo._id)
						.field(
							"userNm,userType,userStatus,email,classIds,assistance,password,studentIds,ballTeamNm,ballTeamType,companyAddress,portrait,phone,jerseyNum,height,weight,gender,socialNo,socialImg,isLocal,identityCardNo,identityCardImg,identityCardImgB,isLocalProperty,propertyImg,opinion,originalTeam"
						)
						.get().then((res) => {
							const userInfo = res.result.data[0]
							uni.setStorage({
								key: 'userInfo',
								data: userInfo || {},
								success: function() {
									console.log('success-报名成功后计入setStorage', userInfo);
									uni.getStorage({
										key: 'userInfo',
										success: function(res) {
											_this.userInfo = res.data
											console.log(res.data)
										}
									})
								}
							})
						})
				})
			},
			// 删除图片
			delImg(e) {
				this.imgList = e
			},
			// 上传成功
			imgSuccess(e) {
				this.formData.portrait = e
				console.log('上传成功', e, this.formData.portrait)
			},
			editBtn() {
				this.btnFla = false
			},
			restBtn() {
				this.formData = {
					portrait: '',
					stdNm: '',
					gender: '',
					age: '',
					height: '',
					weight: '',
					phone: '' // 报名人手机
				}
			},
			confirmBtn() {
				const _this = this
				const parm = {
					courseId: this.tranObj.id,
					title: this.tranObj.title,
					courseLevel: this.tranObj.classLevel,
					courseStatus: this.tranObj.state,
					learnerNm: this.formData.stdNm,
					learnerId: this.formData.learnerId, // 学员证件号
					applicationPhone: this.userInfo.phone,
					payStatus: '0',
					tuition: this.tranObj.tuition,
					allClassTime: this.tranObj.allClassTime,
					classId: null,
					deleted_at: null,
					created_date: new Date().getTime(),
					updated_date: null,
					created_by: this.userInfo.userNm
				}
				const studParm = {
					portrait: this.formData.portrait,
					stdNm: this.formData.stdNm,
					learnerId: this.formData.learnerId, // 学员证件号
					gender: this.formData.gender,
					phone: this.userInfo.phone,
					age: this.formData.age,
					height: this.formData.height,
					weight: this.formData.weight,
					deleted_at: null,
					created_date: new Date().getTime(),
					updated_date: null,
					created_by: this.userInfo.userNm
				}
				if (!verifyForm(studParm)) return
				if (!checkFontRule(this.formData.learnerId, '1')) return
				uni.showLoading({
					mask: true
				});
				console.log(parm, studParm)
				this.getCourseRegister(this.userInfo, this.tranObj.id, parm).then(res => {
					if (res) {
						const where =
							`"phone"=="${_this.userInfo.phone}"&&"stdNm"=="${_this.formData.stdNm}"&&"learnerId"=="${studParm.learnerId}"`
						return db.collection('student-MGMT').where(where)
							.field('phone,stdNm').get().then((res) => {
								const data = res.result.data[0]
								_this.updateUserInfo({
									cid: this.tranObj.id,
									sid: this.formData.learnerId
								})
								if (!data) {
									return db.collection('student-MGMT').add(studParm).then((
										res) => {
										uni.showToast({title: '报名成功去支付！'})
										uni.hideLoading()
										// 微信不让过晚点再上
										// uni.navigateTo({
										// 	url: `../train/payEQCode`
										// });
									}).catch((err) => {
										uni.showModal({
											content: err.message || '请求服务失败',
											showCancel: false,
										})
										uni.hideLoading()
									})
								} else {
									uni.hideLoading()
									// uni.navigateTo({
									// 	url: `../train/payEQCode`
									// });
								}
							})
					} else {
						uni.hideLoading()
					}
				})
				// setTimeout(() => uni.navigateBack(), 2283)
			}
		}
	}
</script>

<style>
	.reg-page {}

	.input-title {
		width: 45%;
		display: inline-block;
		vertical-align: top;
	}

	.img-sty {
		width: 60%;
		height: 68px;
		display: inline-block;
	}

	.input-sty {
		display: inline-block;
		vertical-align: middle;
	}

	.is-disabled {
		width: 50%;
		color: #888;
	}

	.form-sty {
		width: 100%;
		height: 70px;
		border-bottom: 1px solid #dcdfe6;
		line-height: 70px;
		padding: 0 5px;
	}

	.btn-area {
		width: 150px;
		text-align: center;
		flex: 1;
	}

	.btn-sty {
		width: 150px;
		height: 38px;
		color: #fc993b;
		background: #ffffff;
		border: 1px solid #fc993b;
		border-radius: 20px;
		line-height: 38px;
		margin: 0 auto;
	}

	.bi-shu-sty::before {
		content: '*';
		position: relative;
		top: 0;
		left: 0;
		color: red;
	}
</style>
<style lang="scss">
</style>